package com.lcy.servlet;

import com.lcy.entry.SmbmsUser;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class HomeServlet   extends HttpServlet {

    //推到推理出
    //写web 项目功能  退出登录，删除用户，修改改用，修改密码
    //1.连接数据库，操作数据，对数据的增删改查    dao层
    //2.对数据返回的数据，进行处理。            service
    //3.跳转页面                             servlet  表现层
    // 数据载体，实体类
    //分层概念
    //web页面===>servlet ===>service ===>dao ===>mysqldb
    //web页面<===servlet <====service<====dao<===


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //组织准备数据的代码写这里
        //第一步，加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //第二步 获得连接
            String url = "jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8";
            String userRoot = "root";
            String userPwd = "123456";
            Connection connection = DriverManager.getConnection(url, userRoot, userPwd);
            String sql = "select * from smbms_user ";
            PreparedStatement pst = connection.prepareStatement(sql);
            ResultSet resultSet = pst.executeQuery();
            List<SmbmsUser> smbmsUserList  = new ArrayList<>();
            //取数据库当中的数据赋值 smbmsUser
            while (resultSet.next()){
                SmbmsUser  smbmsUser = new SmbmsUser();
                String userCode =    resultSet.getString("userCode");
                String userName =     resultSet.getString("userName");
                String userPassword =     resultSet.getString("userPassword");
                //重数据库里查出的数据，赋值Java类对象
                smbmsUser.setUserCode(userCode);
                smbmsUser.setUserName(userName);
                smbmsUser.setUserPassword(userPassword);
                smbmsUserList.add(smbmsUser);
            }
            HttpSession session = req.getSession();
            session.setAttribute("smbmsUserList",smbmsUserList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        resp.sendRedirect("home.jsp");
    }

}
